#!/user/bin/env python3
# -*- coding: utf-8 -*-
"""
--------------------------------------
    Author:     JiChao_Song
    Date  :     2020/12/11 16:54
    Desc  :
--------------------------------------
"""
from flask import Blueprint, request
from application import app
from common.libs.JsonResponseUtils import JsonResponse
from common.libs.JwtUtils import verify_jwt
from common.libs.QuerySetUtils import QuerySetUtils
from servers.models.projectModel import Project
from servers.servers.ProjectServices import add_valid_project, organize_add_project, ProjectServices
from servers.servers.UserServices import user_add_project

project_organize_route = Blueprint('organizeproject', __name__)


# 项目列表
@project_organize_route.route('/list', methods=['POST'])
def projectList():
    try:

        # 1. 从请求头中获取用户信息
        accesstoken = request.headers.get('accesstoken')
        if verify_jwt(accesstoken) is None:
            return JsonResponse(code=40004, data=None, message="accesstoken失效").jsonExit()
        username = verify_jwt(accesstoken).get('username')
        id = verify_jwt(accesstoken).get('id')
        print('用户id:', id)
        # 2. 查询当前用户的项目列表
        form = {} if not request.json else dict(request.json)
        form['projectUsername'] = username
        data = ProjectServices().pagination(**form)
        return JsonResponse(code = 20000, data = data, message = '请求成功').jsonExit()

    except Exception as e:
        app.logger.error(e)
        return JsonResponse(code=50000, data=None, message="系统异常", errors=f'{e}').jsonExit()


# 项目新增
@project_organize_route.route('/add', methods=['POST'])
def projectAdd():
    try:
        # 1. 从请求头中获取用户信息
        accesstoken = request.headers.get('accesstoken')
        if verify_jwt(accesstoken) is None:
            return JsonResponse(code=40004, data=None, message="accesstoken失效").jsonExit()
        username = verify_jwt(accesstoken).get('username')
        phone = verify_jwt(accesstoken).get('phone')
        form = {} if not request.json else dict(request.json)
        form = QuerySetUtils(Project).filterField(form)
        form['projectUsername'] = username
        form['projectUserphone'] = phone
        is_valid = organize_add_project(**form)
        if is_valid:
            return is_valid
        project = Project(**form)
        project.save()
        user_add_project(username=username, phone=phone,
                         projectName=form.get('projectName'))
        return JsonResponse(code=20000, data=project, message="请求成功").jsonExit()
    except Exception as e:
        app.logger.error(e)
        return JsonResponse(code=50000, data=None, message="系统异常", errors=f'{e}').jsonExit()


# 项目详情
@project_organize_route.route('/info', methods=['POST'])
def projectInfo():

    try:
        form = {} if not request.json else dict(request.json)
        projectName = form.get('projectName')
        if projectName is None or projectName == "":
            return JsonResponse(code=40007, data=None, message="projectName不能为空").jsonExit()
        project = Project.objects(projectName=projectName)
        if projectName.count() == 0:
            return JsonResponse(code=40007, data=None, message="项目不存在").jsonExit()
        return JsonResponse(code=20000, data=project, message="请求成功").jsonExit()

    except Exception as e:
        app.logger.error(e)
        return JsonResponse(code=50000, data=None, message="系统异常", errors=f'{e}').jsonExit()


# 项目详情
@project_organize_route.route('/edit', methods=['POST'])
def projectEdit():

    try:
        form = {} if not request.json else dict(request.json)
        form = QuerySetUtils(Project).filterField(form)

        if form.get("id") is None or form.get("id") == "":
            return JsonResponse(code=40002, data=None, message="id不能为空").jsonExit()
        project = Project.objects(id=form.get('id'))
        if project.count() == 0:
            return JsonResponse(code=40007, data=None, message="项目不存在").jsonExit()
        project.update(**form)
        return JsonResponse(code=20000, data=project, message="请求成功").jsonExit()

    except Exception as e:
        app.logger.error(e)
        return JsonResponse(code=50000, data=None, message="系统异常", errors=f'{e}').jsonExit()


# 项目详情
@project_organize_route.route('/delete', methods=['POST'])
def projectDelete():

    try:
        form = {} if not request.json else dict(request.json)
        if form.get("id") is None or form.get("id") == "":
            return JsonResponse(code=40002, data=None, message="id不能为空").jsonExit()
        project = Project.objects(id=form.get('id'))
        if project.count() == 0:
            return JsonResponse(code=40007, data=None, message="项目不存在").jsonExit()
        project.delete()
        return JsonResponse(code=20000, data=project, message="请求成功").jsonExit()

    except Exception as e:
        app.logger.error(e)
        return JsonResponse(code=50000, data=None, message="系统异常", errors=f'{e}').jsonExit()
